import time
from concurrent.futures.thread import ThreadPoolExecutor

import requests


def download_picture(picture_url):
    resp = requests.get(picture_url)
    if resp.status_code == 200:
        filename = picture_url[picture_url.rfind('/') + 1:]
        with open(f'images/{filename}', 'wb') as file:
            file.write(resp.content)


def main():
    # 线程池
    with ThreadPoolExecutor(max_workers=16) as pool:
        futures = []
        start = time.time()
        key = 'e8c5524dd2a365f20908ced735f8e480'
        for page in range(1, 6):
            resp = requests.get(f'http://api.tianapi.com/meinv/index?key={key}&page={page}&num=10')
            beauty_list = resp.json()['newslist']
            for beauty in beauty_list:
                picture_url = beauty['picUrl']
                # 将耗时间的任务放到线程池中交给线程来执行
                f = pool.submit(download_picture, picture_url)
                futures.append(f)
        for f in futures:
            f.result()
        end = time.time()
        print(f'执行时间: f{end - start:.3f}秒')


if __name__ == '__main__':
    main()
